<?php
namespace api\modules\shop\controllers;

use common\models\Code;
use common\models\Shop;
use common\models\ShopCollection;
use common\models\ShopUser;
use common\models\SupplierGoods;
use common\models\Contact;
use common\service\ConstantService;
use common\service\GlobalUrlService;
use common\service\SmsService;
use common\service\SupplierGoodsService;
use common\service\WechatService;

class ShopController extends ShopBaseController
{
    /**
     * 自动登录
     */
    public function actionAutoLogin(){
        if($this->isGet()){
            $code = $this->get('code');
            $appid = \Yii::$app->params['shop_wechat']['appid'];
            $secret = \Yii::$app->params['shop_wechat']['secret'];
            $request = WechatService::getWechatOpenid($code,$appid,$secret);
            $request = json_decode($request,true);
            if(isset($request['errcode'])){
                return $this->renderJson([],'code无效',ConstantService::$response_fail);
            }
            $openid = $request['openid'];
            $shop = ShopUser::find()->where(['openid'=>$openid])->asArray()->one();
            if(empty($shop)){
                //用户不存在入库
                $shopuser_model = new ShopUser();
                $data['openid'] = $openid;
                $data['create_time'] = time();
                $shopuser_model->setAttributes($data);
                if(!($shopuser_model->save())){
                    return $this->renderJson([],'用户信息存储失败',ConstantService::$response_fail);
                }
            }
            //最终都返回Token
            $token = base64_encode(base64_encode($openid).'-'.$this->salt);
//            if(!$shop){
//                return $this->renderJson($token,'需要绑定',ConstantService::$response_fail_auth);
//            }
            if(empty($shop['nickname']) && empty($shop['avatarurl'])){
                return $this->renderJson($token,'该用户未授权',ConstantService::$response_fail_auth);
            }
            return $this->renderJson($token,'操作成功',ConstantService::$response_success);
        }
        return $this->renderJson([],'参数错误',ConstantService::$response_fail);
    }

    /**
     * 更新用户信息
     */
    public function actionSaveUserInfo(){
        if($this->isPost()){
            $data = $this->post();
            $user_id = $this->shop['id'];
            //这里需要把微信头像存到我们这边
            $user_model = ShopUser::findOne(['id'=>$user_id]);
            $user_model['avatarurl'] = WechatService::getUserHeader($data['url']);
            $user_model['nickname'] = base64_encode($data['nickname']);
            $user_model['update_time'] = time();
            if($user_model && $user_model->save()){
                return $this->renderJson([],'保存成功',ConstantService::$response_success);
            }
            return $this->renderJson([],'保存失败',ConstantService::$response_fail);
        }
        return $this->renderJson([],'参数错误',ConstantService::$response_fail);
    }

    /**
     * 管理员绑定
     */
    public function actionSaveShopInfo(){
        if($this->isPost()){
            $token = isset(\Yii::$app->request->headers['Auth']) ? \Yii::$app->request->headers['Auth']:'';
            $token = explode('-',base64_decode($token));
            $openid = base64_decode($token[0]);
            $phone = $this->post('phone');
            $code = $this->post('code');

            $shop_model = Shop::find()->where(['admin_phone'=>$phone])->one();
            if(!$shop_model){
                return $this->renderJson([],'该账号不存在',ConstantService::$response_fail);
            }
            if($shop_model['status'] != 1){
                return $this->renderJson([],'该账号不存在状态不正确,请联系管理员',ConstantService::$response_fail);
            }
            if(!empty($shop_model['openid']) && !empty($shop_model['user_id'])){
                return $this->renderJson([],'该账号已绑定',ConstantService::$response_fail);

            }
            //判断验证码是否正确
            $msg = $this->_checkcode($phone,$code);
            if(!is_int($msg)){
                return $this->renderJson([],$msg,ConstantService::$response_fail);
            }
            $shop_model->openid = $openid;
            $shop_model->user_id = $this->shop['id'];
            if($shop_model->save()){
                $Codes = Code::findOne(['id'=>$msg]);
                $Codes->is_del = 1;
                $Codes->save();
                $user = ShopUser::findOne(['id'=>$this->shop['id']]);
                $user->shop_id = $shop_model['id'];
                $user->save();
                return $this->renderJson([],'绑定成功',ConstantService::$response_success);
            }
            return $this->renderJson([],'操作失误,请重试',ConstantService::$response_fail);
        }
        return $this->renderJson([],'参数错误',ConstantService::$response_fail);
    }

    /**
     * 发送短信验证码
     */
    public function actionSendCode(){
        if($this->isPost()){
            $phone = $this->post('phone');
            if(!preg_match('/^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|17[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\\d{8}$/',$phone))
            {
                return $this->renderJson([],'请输入正确的管理员手机号',ConstantService::$response_fail);
            }
            if(!$phone){
                return $this->renderJson([],'参数错误',ConstantService::$response_fail);
            }
            $shop = Shop::findOne(['admin_phone'=>$phone]);
            if(!empty($shop['openid'])){
                return $this->renderJson([],'改账号已被绑定',ConstantService::$response_fail);
            }
            $data = Code::find()->where(['phone'=>$phone])->orderBy(['id'=>SORT_DESC])->one();
            if((time()-$data['time'])>90){
                Code::updateAll(['is_del'=>1],['phone'=>$phone]);
                $code = SmsService::addSms($phone);
                //调用发送短信方法
                if($code){
                    return $this->renderJson([],'发送成功',ConstantService::$response_success);
                }else{
                    return $this->renderJson([],'系统错误稍后再试',ConstantService::$response_fail);
                }
            }else{
                return $this->renderJson([],'请90秒后再试一试',ConstantService::$response_fail);
            }
        }
        return $this->renderJson([],'接口错误',ConstantService::$response_fail);
    }


    /**
     * 验证验证码是否正确
     * @param $phone
     * @param $code
     * @return string
     */
    private function _checkcode($phone,$code){
        if(empty($phone)){
            return '管理员手机号不能为空!';
        }
        if( empty($code)){
            return '验证码不能为空!';
        }
        $data = Code::find()->where(['phone'=>$phone])->orderBy(['id'=>SORT_DESC])->asArray()->one();
        if((time()-$data['time'])>300 || $data['is_del'] == 1){
            return '验证码错误';
        }
        if($data['code'] == $code){

            return (int)$data['id'];
        }else{
            return '验证码错误';
        }
    }

    /**
     * 获取用户信息
     */
    public function actionGetUser(){
        if($this->isGet()){
            $shop_user = $this->shop;
            $shop = [];
            if(!empty($shop_user['shop_id'])){
                $shop = Shop::find()->where(['id'=>$shop_user['shop_id']])->asArray()->one();
                $shop['shop_logo'] = GlobalUrlService::buildCdnUrl($shop['shop_logo']);
                $shop['shop_id'] = $shop['id'];

            }else{
                $shop['shop_name'] = base64_decode($shop_user['nickname']);
                $shop['shop_logo'] = GlobalUrlService::buildCdnUrl($shop_user['avatarurl']);
                $shop['shop_id'] = $shop_user['shop_id'];
            }
            //这个地方需要加一个商家联系方式
            $phone = Contact::find()->where(['id'=>1])->asArray()->one();
            $shop['phone'] = $phone['phone'];
            return $this->renderJson($shop,'',ConstantService::$response_success);
        }
        return $this->renderJson([],'参数错误',ConstantService::$response_fail);
    }

    /**
     * 添加收藏
     */
    public function actionAddCollection(){
        if($this->isGet()){
            $goods_id = $this->get('goods_id');
            if(empty($goods_id)){
                return $this->renderJson([],'参数错误',ConstantService::$response_fail);
            }
            $model = new ShopCollection();
            $data = [];
            $data['goods_id'] = $goods_id;
            $data['shop_id'] = $this->shop['id'];
            $data['status'] = 1;
            $data['is_del'] = 0;
            $data['create_time'] = time();
            $data['update_time'] = time();
            $model->setAttributes($data);
            if($model->save()){
                $id = \Yii::$app->db->getLastInsertID();
                return $this->renderJson(['collection_id'=>$id],'收藏成功',ConstantService::$response_success);
            }
            return $this->renderJson([],'收藏失败',ConstantService::$response_fail);
        }
        return $this->renderJson([],'参数错误',ConstantService::$response_fail);
    }

    /**
     * 取消收藏 或者浏览记录
     */
    public function actionDelCollection(){
        if($this->isGet()){
            $id = $this->get('id');
            if(empty($id)){
                return $this->renderJson([],'参数错误',ConstantService::$response_fail);
            }
           $query = ShopCollection::findOne(['id'=>$id]);
            $query->is_del = 1;
            if($query->save()){
                return $this->renderJson([],'操作成功',ConstantService::$response_success);
            }
            return $this->renderJson([],'操作失败',ConstantService::$response_fail);
        }
        return $this->renderJson([],'参数错误',ConstantService::$response_fail);
    }
    /**
     * 获取店铺收藏 或者浏览记录
     */
    public function actionGetCollection(){
        if($this->isGet()){
            $p = intval( $this->get('page',1));
            $status = $this->get('status');
            $offset = ($p - 1) * $this->page_size;
            $collections = ShopCollection::find()
                ->where(['is_del'=>0,'shop_id'=>$this->shop['id'],'status'=>$status])
                ->asArray()
                ->offset( $offset )
                ->limit( $this->page_size )
                ->all();
            if(!empty($collections)){
                $goods_id = array_column($collections,'goods_id');

                $goods = SupplierGoods::find()
                    ->select(['id','goods_name','is_del','status','list_img','goods_type','display_sales'])
                    ->where(['id'=>$goods_id])
                    ->asArray()
                    ->all();
                $goods = SupplierGoodsService::GetAttrListPrice($goods);

                $new_goods = [];
                foreach ($goods as $item){
                    $new_goods[$item['id']] = $item;
                }
                unset($item);
                foreach ($collections as &$item){
                    $item['goods'] = '';
                    if(isset($new_goods[$item['goods_id']]) && !empty($new_goods[$item['goods_id']])){
                        $item['goods'] = $new_goods[$item['goods_id']];
                    }
                }

            }
            return $this->renderJson($collections,'',ConstantService::$response_success);

        }
        return $this->renderJson([],'参数错误',ConstantService::$response_fail);

    }



}